package seg.tef4.whms.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.scan.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import seg.tef4.whms.activity.activityinit.SubBaseActivity;
import seg.tef4.whms.apis.EquipmentApi;
import seg.tef4.whms.apis.OutWarehouseApi;
import seg.tef4.whms.component.OutWarehouseRecycleView;
import seg.tef4.whms.component.ReturnSearchRecycleView;
import seg.tef4.whms.domain.TOutWarehouse;
import seg.tef4.whms.domain.TSparePart;
import seg.tef4.whms.domain.entity.SysUser;
import seg.tef4.whms.util.auth.OnlineUser;
import seg.tef4.whms.util.dialog.AlertDialogCreator;
import seg.tef4.whms.util.retrofitutil.RetrofitUtil;

public class ReturnSearchActivity extends SubBaseActivity {

    /**
     * 整体布局
     **/
    private DrawerLayout out_warehouse_drawer_layout;
    private LinearLayout out_warehouse_filter_drawer;
    private LinearLayout out_warehouse_filter_main;

    /**
     * 下拉列表
     **/
    private Spinner out_warehouse_line_spinner;
    private Spinner out_warehouse_station_spinner;
    // private Spinner out_warehouse_out_type_spinner;
    private Spinner out_warehouse_status_spinner;

    /** 查询filter **/
    private EditText out_warehouse_material_no_editview;

    private EditText out_warehouse_out_time_start;

    private EditText out_warehouse_out_time_end;



    private EquipmentApi equipmentApi = (EquipmentApi)  RetrofitUtil.getApiInstance(EquipmentApi.class);

    private OutWarehouseApi outWarehouseApi = (OutWarehouseApi)  RetrofitUtil.getApiInstance(OutWarehouseApi.class);


    /** 分页属性 **/
    private int pageNum = 1;

    private int pageSize = 200;

    private List<TOutWarehouse> tOutWarehouses;

    private Long total = Long.MAX_VALUE;

    private RecyclerView recyclerView;

    /** 按钮 **/


    private Button out_warehouse_filter_button;
    private Button out_warehouse_search_button;

    private Button out_warehouse_reset_button;

    private Button out_warehouse_top_button;





    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_search);
        /**
         * 整体布局
         **/
        out_warehouse_drawer_layout = findViewById(R.id.out_warehouse_drawer_layout);
        out_warehouse_filter_drawer = findViewById(R.id.out_warehouse_filter_drawer);
        out_warehouse_filter_main = findViewById(R.id.out_warehouse_filter_main);
        /**
         * 下拉列表
         **/
        out_warehouse_line_spinner = findViewById(R.id.out_warehouse_line_spinner);
        out_warehouse_station_spinner = findViewById(R.id.out_warehouse_station_spinner);
        // out_warehouse_out_type_spinner = findViewById(R.id.out_warehouse_out_type_spinner);
        out_warehouse_status_spinner = findViewById(R.id.out_warehouse_status_spinner);

        /** 查询filter **/
        out_warehouse_material_no_editview = findViewById(R.id.out_warehouse_material_no_editview);

        /** button **/
        out_warehouse_search_button = findViewById(R.id.out_warehouse_search_button);
        out_warehouse_reset_button = findViewById(R.id.out_warehouse_reset_button);
        out_warehouse_filter_button = findViewById(R.id.out_warehouse_filter_button);
        out_warehouse_top_button = findViewById(R.id.out_warehouse_top_button);



        tOutWarehouses = new ArrayList<>();
        recyclerView = findViewById(R.id.out_warehouse_RecyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(ReturnSearchActivity.this);
        recyclerView.setLayoutManager(layoutManager);

        spinnerInit();
        dateSelectorInit();
        out_warehouse_filter_button.setOnClickListener(view -> {
            drawerControl();
        });

        out_warehouse_top_button.setOnClickListener(view -> {
            recyclerView.scrollToPosition(0);
        });



        DataInit();
        out_warehouse_search_button.setOnClickListener(view -> {
            // drawerControl();
            this.queryOutWarehouse(true);

        });

        out_warehouse_reset_button.setOnClickListener(view -> {
            ReturnSearchActivity.this.pageNum = 1;
            ReturnSearchActivity.this.total = Long.MAX_VALUE;
            out_warehouse_material_no_editview.setText(null);
            out_warehouse_out_time_start.setText("");
            out_warehouse_out_time_end.setText("");
            out_warehouse_line_spinner.setSelection(0);
            out_warehouse_station_spinner.setSelection(0);
            // out_warehouse_out_type_spinner.setSelection(0);
            out_warehouse_status_spinner.setSelection(0);
            queryOutWarehouse(true);
        });


    }

    /**
     * 日期选择初始化
     */
    private void dateSelectorInit(){
        out_warehouse_out_time_start = findViewById(R.id.out_warehouse_out_time_start);
        out_warehouse_out_time_end = findViewById(R.id.out_warehouse_out_time_end);
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();
        out_warehouse_out_time_start.setOnClickListener(v -> {
            new DatePickerDialog(
                    ReturnSearchActivity.this,R.style.CustomDatePickerDialog,
                    (view, year, month, dayOfMonth) -> {
                        startCalendar.set(Calendar.YEAR, year);
                        startCalendar.set(Calendar.MONTH, month);
                        startCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                        if (out_warehouse_out_time_start.getText().toString().equals("") || endCalendar.after(startCalendar)){
                            out_warehouse_out_time_start.setText(year+"-"+(month+1)+"-"+dayOfMonth);
                        }else{
                            out_warehouse_out_time_start.setText("");
                            out_warehouse_out_time_end.setText("");
                            AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                                    "系统提示", "结束时间不能早于开始时间", "确认", null).show();
                        }
                    },
                    startCalendar.get(Calendar.YEAR),
                    startCalendar.get(Calendar.MONTH),
                    startCalendar.get(Calendar.DAY_OF_MONTH)
            ).show();
        });

        out_warehouse_out_time_end.setOnClickListener(v -> new DatePickerDialog(
                ReturnSearchActivity.this,R.style.CustomDatePickerDialog,
                (view, year, month, dayOfMonth) -> {
                    endCalendar.set(Calendar.YEAR, year);
                    endCalendar.set(Calendar.MONTH, month);
                    endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    if (out_warehouse_out_time_start.getText().toString().equals("") ||endCalendar.after(startCalendar)){
                        out_warehouse_out_time_end.setText(year+"-"+(month+1)+"-"+dayOfMonth);
                    }else{
                        out_warehouse_out_time_start.setText("");
                        out_warehouse_out_time_end.setText("");
                        AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                                "系统提示", "结束时间不能早于开始时间", "确认", null).show();
                    }

                },
                endCalendar.get(Calendar.YEAR),
                endCalendar.get(Calendar.MONTH),
                endCalendar.get(Calendar.DAY_OF_MONTH)
        ).show());
    }

    public static void startOutWarehouseActivity(Context context) {
        context.startActivity(new Intent(context, ReturnSearchActivity.class));
    }

    /**
     * @description 侧边栏初始化
     */
    private void drawerControl() {
        if (out_warehouse_drawer_layout.isDrawerOpen(out_warehouse_filter_drawer))
            out_warehouse_drawer_layout.closeDrawer(out_warehouse_filter_drawer);
        else
            out_warehouse_drawer_layout.openDrawer(out_warehouse_filter_drawer);
    }

    /**
     * @description 产线选择项初始化
     */
    private void spinnerInit() {
        // 获取产线的所有选项
        equipmentApi.getProductLine(OnlineUser.getToken(ReturnSearchActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ReturnSearchActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        out_warehouse_line_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });
        // 设置监听
        out_warehouse_line_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String selected_line = (String) adapterView.getItemAtPosition(i);
                // 获取对应产线的所有工位
                equipmentApi.getStation(OnlineUser.getToken(ReturnSearchActivity.this), selected_line).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String resultJson = response.body().string();
                            JSONObject result = new JSONObject(resultJson);
                            int code = result.getInt("code");
                            String msg = result.getString("msg");
                            if (code == 200) {
                                JSONArray jsonArrays = result.getJSONArray("rows");
                                List<String> lines = new ArrayList<>();
                                lines.add("【请选择】");
                                for (int i = 0; i < jsonArrays.length(); i++) {
                                    JSONObject jsonObject = jsonArrays.getJSONObject(i);
                                    String name = jsonObject.getString("name");
                                    String equipmentName = jsonObject.getString("value");
                                    lines.add(name+"\n"+equipmentName);
                                }
                                ArrayAdapter<String> adapter = new ArrayAdapter<String>(ReturnSearchActivity.this,
                                        R.layout.spinner_item, lines);
                                adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
                                out_warehouse_station_spinner.setAdapter(adapter);
                            } else {
                                throw new RuntimeException(code + ":" + msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                                    "系统错误", e.toString(), "确认", null).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                                "系统错误", t.toString(), "确认", null).show();
                    }
                });

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        // 出库类型
        /*equipmentApi.getOutType(OnlineUser.getToken(ReturnSearchActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ReturnSearchActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        out_warehouse_out_type_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });*/

        // 状态
        outWarehouseApi.get_status(OnlineUser.getToken(ReturnSearchActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            // 过滤掉出库标签
                            if(name.equals("出库"))
                                continue;
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ReturnSearchActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        out_warehouse_status_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });


    }

    private void DataInit(){
        queryOutWarehouse(true);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    ReturnSearchActivity.this.pageNum +=1;
                    queryOutWarehouse(false);

                }

            }
        });


    }

    /**
     * @description 零件查询
     */
    private void queryOutWarehouse(boolean initMark){
        if(!initMark && (long) pageNum * pageSize >= total)
            return;
        Map<String,String> params = new HashMap<>();
        params.put("pageNum",String.valueOf(pageNum));
        params.put("pageSize",String.valueOf(pageSize));
        String materialNo = this.out_warehouse_material_no_editview.getText().toString();
        if(materialNo == null || materialNo.trim().equals(""))
            materialNo = null;
        String out_time_start = this.out_warehouse_out_time_start.getText().toString();
        if(out_time_start == null || out_time_start.trim().equals(""))
            out_time_start = null;
        String out_time_end = this.out_warehouse_out_time_end.getText().toString();
        if(out_time_end == null || out_time_end.trim().equals(""))
            out_time_end = null;
        String line = this.out_warehouse_line_spinner.getSelectedItem() == null ?
                null : this.out_warehouse_line_spinner.getSelectedItem().toString();
        if(line !=null && line.equals("【请选择】"))
            line = null;
        String station = this.out_warehouse_station_spinner.getSelectedItem() == null ?
                null : this.out_warehouse_station_spinner.getSelectedItem().toString();
        if(station!=null && station.equals("【请选择】"))
            station = null;
/*        String out_type = this.out_warehouse_out_type_spinner.getSelectedItem() == null ?
                null : this.out_warehouse_out_type_spinner.getSelectedItem().toString();
        if(out_type!=null && out_type.equals("【请选择】"))
            out_type = null;*/
        String status = this.out_warehouse_status_spinner.getSelectedItem() == null ?
                null : this.out_warehouse_status_spinner.getSelectedItem().toString();
        if(status!=null && status.equals("【请选择】"))
            status = null;
        if(materialNo!=null)
            params.put("materialNo",materialNo);
        if(line!=null)
            params.put("line",line);
        if(station!=null)
            params.put("station",station.split("\n")[0]);
/*        if(out_type!=null)
            params.put("outType",out_type);*/
        if(status!=null){
            if(status.equals("出库"))
                params.put("status", String.valueOf(0));
            else if(status.equals("待一级审批"))
                params.put("status", String.valueOf(1));
            else if(status.equals("待二级审批"))
                params.put("status", String.valueOf(2));
            else if(status.equals("退库"))
                params.put("status", String.valueOf(3));
        }

        if(out_time_start!=null)
            params.put("params[beginTime]",out_time_start);
        if(out_time_end!=null)
            params.put("params.[endTime]",out_time_end);
        // 限制只能查自己
        params.put("createBy",OnlineUser.getSysUser().getUserName());
        outWarehouseApi.list(OnlineUser.getToken(ReturnSearchActivity.this),params).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    total = result.getLong("total");
                    if (code == 200) {
                        if(initMark)
                            tOutWarehouses.clear();
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            TOutWarehouse tOutWarehouse = new TOutWarehouse();
                            tOutWarehouse.setId(jsonObject.getLong("id"));
                            tOutWarehouse.setMaterialNo(jsonObject.getString("materialNo"));
                            tOutWarehouse.setCreateBy(jsonObject.getString("createBy"));
                            tOutWarehouse.setCreateTimeStr(jsonObject.getString("createTime"));
                            tOutWarehouse.setOutNum(jsonObject.getLong("outNum"));
                            tOutWarehouse.setLine(jsonObject.getString("line"));
                            tOutWarehouse.setStation(jsonObject.getString("station"));
                            tOutWarehouse.setOutType(jsonObject.getString("outType"));
                            tOutWarehouse.setStatus(jsonObject.getInt("status"));
                            // 过滤掉 未进行退库审核流程的备件
                            if(tOutWarehouse.getStatus() == 0L)
                                continue;
                            // spare_part
                            TSparePart tSparePart = new TSparePart();
                            JSONObject tSparePartJson = jsonObject.getJSONObject("tSparePart");
                            tSparePart.setName(tSparePartJson.getString("name"));
                            tSparePart.setBrand(tSparePartJson.getString("brand"));
                            tSparePart.setSpecification(tSparePartJson.getString("specification"));
                            tSparePart.setLocation(tSparePartJson.getString("location"));
                            tOutWarehouse.settSparePart(tSparePart);
                            // sysuser
                            SysUser sysUser = new SysUser();
                            JSONObject sysUserJson = jsonObject.getJSONObject("sysUser");
                            sysUser.setNickName(sysUserJson.getString("nickName"));
                            tOutWarehouse.setSysUser(sysUser);

                            tOutWarehouses.add(tOutWarehouse);
                        }
                        if(initMark){
                            // 创建并设置布局管理器
                            ReturnSearchRecycleView.RecycleViewAdapter  recycleViewAdapter = new ReturnSearchRecycleView.RecycleViewAdapter(tOutWarehouses);
                            recyclerView.setAdapter(recycleViewAdapter);
                        }else {
                            //通知插入参数是插入位置
                            recyclerView.getAdapter().notifyItemInserted(recyclerView.getAdapter().getItemCount()-1);
                        }
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(ReturnSearchActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });
    }


}
